package com.lxy.mychat1.ui.home;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.lxy.mychat1.Adapter.ChatItemAdapter;
import com.lxy.mychat1.Bean.ChatItem;
import com.lxy.mychat1.Bean.Msg;
import com.lxy.mychat1.Bean.User;
import com.lxy.mychat1.R;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment {
    private ListView chatitemlv;
    ChatItemAdapter adapter;
     List<ChatItem>chatItemList=new ArrayList<>();
     List<User>userList=new ArrayList<>();
     List<Msg>msgList=new ArrayList<>();
     int myid;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        View root = inflater.inflate(R.layout.fragment_home, container, false);
        initData();
        initView(root);

        return root;
    }

    private void initData() {
        SharedPreferences sp=getActivity().getSharedPreferences("userinfo", Context.MODE_PRIVATE);
        myid=sp.getInt("myid",-1);
        userList= LitePal.where("id!=?",myid+"").find(User.class);
        for (User user:userList){
            msgList=getChatContent(user);//我和李四的聊天记录
            if(msgList.size()!=0){
                Msg msg=msgList.get(msgList.size()-1);//如果没有发送新的消息 那么最后一条即为“最新消息”
                ChatItem chatItem=new ChatItem(user.getUserimg(),user.getName(),msg.getContent(),msg.getTime());
                chatItemList.add(chatItem);
            }

        }
    }

    private List<Msg> getChatContent(User user) {
        List<Msg> msgs = new ArrayList<>();
        for (Msg m : LitePal.findAll(Msg.class)) {
            boolean a = myid==m.getSendid() && user.getId() == m.getReceiveid();
            boolean b = myid == m.getReceiveid() && user.getId() == m.getSendid();
            if (a || b) {
                msgs.add(m);

            }
        }
        return msgs;
    }

    private void initView(View root) {
        chatitemlv =root.findViewById(R.id.chatitemlv);
        adapter=new ChatItemAdapter(getContext(),R.layout.chat_item,chatItemList);
        chatitemlv.setAdapter(adapter);


    }
}